package xyz.chaobei.springbootstudy.controller;

import lombok.extern.java.Log;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import xyz.chaobei.springbootstudy.entity.Book;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/book")
@Log
@Validated
public class BookController {

    private List<Book> books = new LinkedList<>();

    @PostMapping("/")
    public ResponseEntity add(@RequestBody @Valid Book book) {
        books.add(book);
        return ResponseEntity.ok(books);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity delete(@PathVariable("id") Integer id) {
        books.remove(id);
        return ResponseEntity.ok(books);
    }

    @PutMapping("/")
    public ResponseEntity update(@RequestBody Book book) {
        List<Book> results = books.stream().filter(book1 -> book1.getId().equals(book.getId())).collect(Collectors.toList());
        books.removeAll(results);
        books.add(book);

        return ResponseEntity.ok(books);
    }

    @GetMapping("/{id}")
    public ResponseEntity get(@Valid @PathVariable("id") @Min(0) Integer id) {
        List<Book> results = books.stream().filter(book1 -> book1.getId().equals(id)).collect(Collectors.toList());
        return ResponseEntity.ok(results);
    }

}
